var DEBUG = true;
var config = {
    Bucket: 'after-sale-1256187897',
    Region: 'ap-guangzhou',
};

/**
 * 上传文件到Cos
 * @author ww
 * @param {json} param 
 */
function uploadToCos(param) {
    //获取文件
    var file = param.file;
    var fileName = param.curTiem + file.name;
    var cos = new COS({
        getAuthorization: function (options, callback) {
            //获取签名认证
            $.get(FILUPLOAD_URL + '/COSSignature', {
                key: encodeURIComponent(fileName)
            }, function (authorization) {
                callback(authorization);
            }, 'text');
        }
    });
    cos.putObject({
        Bucket: config.Bucket,
        Region: config.Region,
        Key: fileName,
        Body: file,
    }, param.success);
}

/**
 * 上传视频到vod
 * @author ww
 * @param {JSON} param
 */
function uploadToVod(param){
    qcVideo.ugcUploader.start({
        videoFile: param.file,//视频，类型为 File
        allowAudio: 1,
        getSignature: function(callback){
            $.post(FILUPLOAD_URL + '/VODSignature',{},function(signature){
                callback(signature); 
            },'text');
        },
        error: function(result){//上传失败时的回调函数
            console.log('上传失败的原因：' + result.msg);
        },
        finish: param.finish
    });
}
/**
 * 根据文件名，获取服务器对象存储的文件路径
 * @author ww
 * @param {String} file 文件名
 * @returns 文件路径
 */
function getCosFile(file){
    if(file){
        return COS_FILE_URL + encodeURI(file);
    }
}
/**
 * 获取pdf文件
 * @param {String} file pdf文件名
 */
// function getPdfFile(file){
//     if(file){
//         return COS_FILE_URL + 'PDF/' + encodeURI(file);
//     }
// }
/**
 * 根据12商品码，获取商品数据
 * @param {String} code 
 */
function getInstructionsInfo(code){
    if(DEBUG){
        code = 'E321-1231-M1';//test
    }
    return 'http://api.axentinfo.com/catalog/product/'+ code +'/specification-info';
}

/**
 * 获取url中参数的方法
 * @author ww
 * @param {String} name 参数名
 * @return 参数值
 */
function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = window.location.search.substr(1).match(reg); //匹配目标参数
    if (r != null) return unescape(r[2]);
    return null; //返回参数值
};

/**
 * pdf文件名
 * @param {String} fileName 
 */
function goShowPDF(fileName){
    //跳转预览pdf的url
    var PDF_PATH_URL = "pages/showPdf.html?pdfFile=https://after-sale-1256187897.cos.ap-guangzhou.myqcloud.com/PDF/";
    if(fileName){
        window.location.href = PDF_PATH_URL + encodeURI(fileName);
    }
}

/**
 * 微信扫码
 * @param {DOM} obj 扫码点击元素
 */
function weChatScan(obj, callback){
    wx.scanQRCode({
        needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
        scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码，默认二者都有
        success: function (res) {
            // 当needResult 为 1 时，扫码返回的结果{resultStr:'DATA_MATRIX,E311-E191-M118130009',errMsg:scanQRCode:ok'}
            //分割扫码结果，截取条形码前12位
            let code = res.resultStr.split(',')[1];
            var result = code ? code.substring(0,12) : 'E321-1231-M1';//test
            $(obj).siblings('input').val(result);
            //获取产品数据
            var url = getInstructionsInfo(result);
            $.get(url, function(product){
                if(product.statusCode === 404){
                    mui.toast('找不到商品!');
                    return false;
                }
                mui.toast(product.productLinkNames[0].split('..pdf')[0]);
                $('input[name=productName]').val(product.productLinkNames[0].split('.pdf')[0]);
                $('input[name=productImage]').val(product.productImage);
            });
        }
    });
}
/**
 * 初始化上传图片事件
 * @param {DOM} elem input 上传文件DOM
 * @param {*} prevDom 显示上传图片的DOM
 */
function uploadInit(elem, prevDom){
	//显示选中图片
	var $uploaderInput = $(elem),
	$prevDom = $(prevDom);

	//点击事件
	$uploaderInput.on("change", function (e) {
		var tmpl='',src, url = window.URL || window.webkitURL || window.mozURL,
			files = e.target.files;
			for (var i = 0, len = files.length; i < len; ++i) {
				var file = files[i];
				if (url) {
					src = url.createObjectURL(file);
				} else {
					src = e.target.result;
                }
                //显示选中图片
                tmpl += '<li class="weui-uploader__file" data-index='+i+' style="background-image:url('+src+')"></li>';
                // image + $(tmpl.replace('#url#', src));
			}
            $prevDom.html($(tmpl));
    });
    //监听图片点击事件
    previewGallery($uploaderInput,$prevDom);
}

/**
 * 预览图片
 * @param {DOM} elem 点击DOM元素
 */
function previewGallery(uploaderInput, prevDom){
	var $gallery = $("#gallery"),
    $galleryImg = $("#galleryImg"),
    prevImageElem;
	prevDom.on("click", "li", function () {
        console.log(this);
        prevImageElem = this;
		$galleryImg.attr("style", this.getAttribute("style"));
        $gallery.fadeIn(100);
	});
	$galleryImg.on("click", function () {
		$gallery.fadeOut(100);
    });
}

//设置cookie的值
function setCookie(key, value) {
	$.cookie(key,value);
}

//获取cookie中的值
function getCookie(key) {
	return $.cookie(key);
}

//将状态转为对应的文本
function stateToTxt(state) {

	switch(state) {
		case REPAIR_STATE_SUBMIT:
			return REPAIR_TXT_SUBMIT;
			break;
		case REPAIR_STATE_AUDIT:
			return REPAIR_TXT_AUDIT;
			break;
		case REPAIR_STATE_BESPEAK:
			return REPAIR_TXT_BESPEAK;
			break;
		case REPAIR_STATE_FEEDBACK:
			return REPAIR_TXT_FEEDBACK;
			break;
		case REPAIR_STATE_SIGN:
			return REPAIR_TXT_SIGN;
			break;
		case REPAIR_STATE_CANCEL:
			return REPAIR_STATE_CANCEL;
			break;
		default:
			break;
	}
}

//工单详情页
function detailRepairRecord(id) {
	window.location.href = "workDetail.html?repairRecordId="+id;
}

//预约上门
function appointment(id) {
	window.location.href = "appointment.html?repairRecordId="+id;
}

//工单反馈
function feedBack(data) {
	window.location.href = "workFeedBack.html?repairRecordId="+data.id+"&workOrderNo="+data.workOrderNo+"&productName="+encodeURI(encodeURI(data.productName));
}

//签名确认
function sign(id) {
	window.location.href = "sign.html?repairRecordId="+id;
}
